const app=getApp()
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function login(){
  wx.login({
    success(res) {
      if (res.code) {
        app.globalData.code = res.code
        console.log(app.globalData.code)
        wx.request({
          url: app.globalData.login_URL, //接收code的api
          data: {
            code: res.code
          },
          success(res) {
            console.log(res)
            if (res && res.header && res.header['Set-Cookie']) {
              wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
              app.globalData.cookie = res.header['Set-Cookie']
              var dataJson = JSON.parse(res.data)
              app.globalData.session_key = dataJson.session_key
              app.globalData.cipherOpenid = dataJson.cipherOpenid
              console.log(app.globalData.session_key)
              console.log(app.globalData.cipherOpenid)
            }
          }
        })
        console.log("登录成功")
        wx.reLaunch({
          url: '../main/main',
        })
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    },
    fail(res) {
      console.log("fail to wx.login")
    }
  })
}

module.exports = {
  formatTime: formatTime,
  login:login
}
